package org.lql.chaos.mq.rabbitmq.config;

import org.lql.chaos.mq.rabbitmq.constant.RabbitMQConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.ExchangeBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: liangqinglong
 * @date: 2025-08-09 13:34
 * @description:
 **/
@Configuration
public class OrderMessageConfig {

	// 订单交换机
	@Bean(RabbitMQConstant.ORDER_EXCHANGE)
	public DirectExchange orderExchange() {
		return ExchangeBuilder.directExchange(RabbitMQConstant.ORDER_EXCHANGE).durable(true).build();
	}

	// 死信交换机
	@Bean(RabbitMQConstant.ORDER_DEAD_EXCHANGE)
	public DirectExchange deadExchange() {
		return ExchangeBuilder.directExchange(RabbitMQConstant.ORDER_DEAD_EXCHANGE).durable(true).build();
	}

	// 正常订单队列（绑定死信交换机）
	@Bean(RabbitMQConstant.ORDER_QUEUE)
	public Queue orderQueue() {
		return QueueBuilder.durable(RabbitMQConstant.ORDER_QUEUE)
				.withArgument("x-dead-letter-exchange", RabbitMQConstant.ORDER_DEAD_EXCHANGE) // 指定死信交换机
				.withArgument("x-dead-letter-routing-key", RabbitMQConstant.ORDER_DEAD_ROUTING_KEY) // 死信路由键
				.withArgument("x-message-ttl", 60 * 1000) // 消息 TTL（毫秒），这里是 60 秒
				.build();
	}

	// 死信队列
	@Bean(RabbitMQConstant.ORDER_DEAD_QUEUE)
	public Queue deadQueue() {
		return QueueBuilder.durable(RabbitMQConstant.ORDER_DEAD_QUEUE).build();
	}

	// 绑定正常订单队列到订单交换机
	@Bean
	public Binding orderBinding(
			@Qualifier(RabbitMQConstant.ORDER_EXCHANGE) DirectExchange exchange,
			@Qualifier(RabbitMQConstant.ORDER_QUEUE) Queue queue
	) {
		return BindingBuilder.bind(queue)
				.to(exchange)
				.with(RabbitMQConstant.ORDER_ROUTING_KEY);
	}

	// 绑定死信队列到死信交换机
	@Bean
	public Binding deadBinding(
			@Qualifier(RabbitMQConstant.ORDER_DEAD_EXCHANGE) DirectExchange exchange,
			@Qualifier(RabbitMQConstant.ORDER_DEAD_QUEUE) Queue deadQueue
	) {
		return BindingBuilder.bind(deadQueue)
				.to(exchange)
				.with(RabbitMQConstant.ORDER_DEAD_ROUTING_KEY);
	}
}
